/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.soc.cs5226.gui.security.util;

import java.io.IOException;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author huijia
 */
public class SessionFilter  implements javax.servlet.Filter{
    public void init(FilterConfig filtercofig) throws ServletException {
        
    }
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain) throws IOException,  ServletException {
        if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            
            HttpSession session = httpServletRequest.getSession(false);
            
            if ((session!=null)&&(session.getAttribute("login")!=null))
            {
                filterchain.doFilter(request, response);
            }
            
            else
            {
                if (httpServletRequest.getPathInfo().indexOf("login.xhtml") < 0)
                {
                    httpServletResponse.sendRedirect("/dashboard/db-monitor/login.xhtml");
                }
                
                filterchain.doFilter(request, response);
            }
        }
        
    }
    public void destroy() {
        
    }
}
